package com.zhanghuan.scheduler.job.service.impl;


import com.zhanghuan.scheduler.job.dao.ScheduleJobLogDao;
import com.zhanghuan.scheduler.job.entity.ScheduleJobLogEntity;
import com.zhanghuan.scheduler.job.service.ScheduleJobLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@Service("scheduleJobLogService")
public class ScheduleJobLogServiceImpl implements ScheduleJobLogService {

    @Autowired
    ScheduleJobLogDao scheduleJobLogDao;

    @Override
    public Map<String,Object> queryPage(Map<String, Object> map) {
        int page = Integer.valueOf((String) map.get("page")) ;
        int limit = Integer.valueOf((String) map.get("limit"));
        String beanName = (String) map.get("beanName");

        if(beanName==null){
            beanName="";
        }
        if( StringUtils.hasLength(beanName.trim()) ){
            int offset = (page-1)*limit;
            List<ScheduleJobLogEntity> content = scheduleJobLogDao.findAllByBeanNameLikeOrderByCreateTimeDesc(beanName,offset,limit);
            long total =scheduleJobLogDao.countAllByBeanNameLike("%"+beanName+"%");
            map.put("content",content);
            map.put("total",total);
        }else{
            PageRequest pageRequest = PageRequest.of(page-1,limit, Sort.by(Sort.Direction.DESC,"createTime"));
            Page pageObj = scheduleJobLogDao.findAll(pageRequest);
            List<ScheduleJobLogEntity> content = pageObj.getContent();
            long total = pageObj.getTotalElements();
            map.put("content",content);
            map.put("total",total);
        }
        return map;
    }
}
